<template>
  <n-card :bordered="false" class="proCard">
    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="1090"
    >
      <template #tableTitle>
        <n-button type="primary" @click="selectGoods">
          <template #icon>
            <n-icon>
              <PlusOutlined />
            </n-icon>
          </template>
          选择商品
        </n-button>
      </template>

      <template #toolbar>
        <n-button type="primary" @click="reloadTable">刷新数据</n-button>
      </template>
    </BasicTable>

    <n-modal
      v-model:show="showSelectGoodsModal"
      class="selectGoodsModal"
      title="选择商品"
      preset="card"
      style="width: 1000px"
      :bordered="false"
      size="huge"
    >
      <n-p> 你选中了 {{ checkedRowKeys.length }} 个商品。 </n-p>
      <n-data-table
        :columns="goodsColumns"
        :data="goodsDataTable"
        :row-key="rowKey"
        :pagination="pagination"
        @update:checked-row-keys="handleCheck"
      />
      <template #action>
        <n-space justify="end">
          <n-button @click="() => (showSelectGoodsModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmGoods">确定</n-button>
        </n-space>
      </template>
    </n-modal>
    <!-- 显示编辑 -->
    <n-modal
      v-model:show="showModal"
      :show-icon="false"
      :mask-closable="false"
      preset="dialog"
      title="编辑活动商品"
    >
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="归属人" path="sellerName">
          <!-- <n-input placeholder="请选择归属人" v-model:value="formParams.sellerName" /> -->
          <n-popselect
            style="width: 800px"
            v-model:value="formParams.sellerName"
            :options="[]"
            trigger="click"
          >
            <n-button>{{ formParams.sellerName || '选择归属人' }}</n-button>
            <template #empty>
              <n-data-table
                :row-key="memberRowKey"
                :columns="memberColumns"
                :data="memberData"
                :pagination="pagination"
                @update:checked-row-keys="handleMemberCheck"
              />
            </template>
            <!-- <template #action>
              <n-space justify="end">
                <n-button type="info" @click="confirmMember">确定</n-button>
              </n-space>
            </template> -->
          </n-popselect>
        </n-form-item>
        <n-form-item label="商品售价" path="price">
          <n-input-number
            placeholder="请输入商品售价"
            :precision="2"
            v-model:value="formParams.price"
          />
        </n-form-item>
        <n-form-item label="商品原价" path="originalPrice">
          <n-input-number
            placeholder="请输入原价"
            :precision="2"
            v-model:value="formParams.originalPrice"
          />
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmEditForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script lang="ts" setup>
  import { onMounted, h, reactive, ref } from 'vue';
  import { useDialog, useMessage, DataTableRowKey } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import {
    getRushPurchaseDetailPage,
    saveRushPurchaseDetails,
    updateRushPurchaseDetail,
    deleteRushPurchaseDetail,
    getGoodsList,
    getMembersList,
  } from '@/api/promotion/rushPurchaseDetail';
  import { columns } from './lib/detailColumns';
  import { goodsColumns } from './lib/goodsColumns';
  import { memberColumns } from './lib/memberColumns';
  import { PlusOutlined } from '@vicons/antd';
  import { ResultEnum } from '@/enums/httpEnum';
  import { useRoute, useRouter } from 'vue-router';

  const route = useRoute();
  const router = useRouter();

  const activityId = ref('');
  const rushPurchaseId = route.params.id;
  const message = useMessage();
  const actionRef = ref();
  const formBtnLoading = ref(false);
  const showSelectGoodsModal = ref(false); // 选择商品
  const showModal = ref(false); // 编辑

  const dialog = useDialog();

  const params = ref({ rushPurchaseId: rushPurchaseId });
  // 商品选择器的key和行
  const checkedRowKeys = ref<DataTableRowKey[]>([]);
  const checkedRow = ref<object[]>([]);

  const actionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
          },
          {
            label: '删除',
            icon: 'ic:outline-delete-outline',
            onClick: handleDelete.bind(null, record),
          },
        ],
      });
    },
  });

  const loadDataTable = async (res) => {
    return await getRushPurchaseDetailPage({ ...params.value, ...res });
  };

  const goodsDataTable = ref([]);
  const memberData = ref([]);

  // 商品选择器的行数据
  type RowData = {
    id: number;
    classifyName: string;
    brandName: string;
    goodsName: string;
    goodsSn: string;
    goodsPrice: number;
  };
  // 指定商品选择器的 key
  const rowKey = (row: RowData) => row.id;

  // 会员选择器的行数据
  type MemberRowData = {
    id: number;
    memberName: string;
    Mobile: string;
    nickname: string;
  };
  // 指定会员选择器的 key
  const memberRowKey = (row: MemberRowData) => row.id;

  // 商品选择每页显示
  const pagination = { pageSize: 5 };
  const formRef: any = ref(null);
  const rules = {
    sellerName: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请选择归属卖家',
    },
    price: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入原价',
      type: 'number',
    },
    originalPrice: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入售价',
      type: 'number',
    },
  };
  const formParams = reactive({
    id: null,
    sellerId: 0,
    sellerName: '',
    sellerMobile: '',
    price: 0,
    originalPrice: 0,
  });
  const formParamsBak = { ...formParams };

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  function reloadTable() {
    actionRef.value.reload();
  }

  function selectGoods() {
    showSelectGoodsModal.value = true;
    getGoodsList({ rushPurchaseId: rushPurchaseId }).then((res) => {
      goodsDataTable.value = res;
    });

    console.log(goodsDataTable.value);
  }

  function confirmEditForm(e) {
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate(async (errors) => {
      if (!errors) {
        let response = await updateRushPurchaseDetail(formParams);
        // 如果是编辑
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
          Object.assign(formParams, formParamsBak);
          showModal.value = false;
          reloadTable();
        } else {
          message.error(msg);
        }
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  async function confirmGoods(e) {
    formBtnLoading.value = true;
    e.preventDefault();
    console.log(checkedRow.value);
    if (checkedRow.value) {
      let data: Array<object> = [];
      for (let i in checkedRow.value) {
        let row = checkedRow.value[i];
        console.log(rushPurchaseId);
        let temp = {
          rushPurchaseId: rushPurchaseId,
          activityId: activityId.value,
          //orderSn: activityId.value + '000' + row.id,
          goodsId: row.id,
          goodsName: row.goodsName,
        };
        data.push(temp);
      }
      console.log(data);
      // let data = [];
      let response = await saveRushPurchaseDetails(data);
      const { message: msg, code } = response;
      if (code == ResultEnum.SUCCESS) {
        message.success(msg);
        showSelectGoodsModal.value = false;
        reloadTable();
      } else {
        message.error(msg);
      }
    }
    formBtnLoading.value = false;
  }

  function handleDelete(record: Recordable) {
    console.log('点击了删除', record);
    dialog.info({
      title: '提示',
      content: `您确定想删除吗?`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        const params = { id: record.id };
        const response = await deleteRushPurchaseDetail(params);
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
          reloadTable();
        } else {
          message.error(msg);
        }
      },
      onNegativeClick: () => {
        message.error('已取消');
      },
    });
  }

  function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    // 每次都清空表单 重新填充
    Object.assign(formParams, formParamsBak);
    Object.assign(formParams, record);
    console.log(formParams);
    showModal.value = true;

    getMembersList().then((res) => {
      console.log('会员列表', res);
      memberData.value = res;
    });
  }

  // 商品选择器选中事件
  function handleCheck(rowKeys: DataTableRowKey[], rows: object[]) {
    checkedRowKeys.value = rowKeys;
    checkedRow.value = rows;
  }

  // 会员选择器选中事件
  function handleMemberCheck(_rowKeys: DataTableRowKey[], rows: MemberRowData[]) {
    let checkedMember = rows[0];
    formParams.sellerName = checkedMember.nickname;
    formParams.sellerMobile = checkedMember.mobile;
    formParams.sellerId = checkedMember.id;
  }

  onMounted(async () => {
    const activityIdRoute = route.params.activityId?.toString();
    if (!activityIdRoute) {
      message.error('系统出现异常，跳转至活动页');
      router.push({
        name: 'rushPurchase',
      });
    }
    activityId.value = activityIdRoute;
  });
</script>

<style lang="less" scoped></style>
